//
//  DeviceView.m
//  Kids
//
//  Created by LiTengFei on 14/11/26.
//  Copyright (c) 2014年 90's Technology Co.Ltd. All rights reserved.
//

#import "DeviceListView.h"

@implementation DeviceListView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self commentInstace];
    }
    return self;
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        [self commentInstace];
    }
    return self;
}

- (void)commentInstace
{

    self.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.7];
    self.showHeight = 70;
}

- (void)showInView:(UIView*)view
{
    NSLog(@"%@", NSStringFromCGRect(view.frame));
    self.frame = CGRectMake(0, CGRectGetHeight(view.frame) - self.showHeight, CGRectGetWidth(view.frame), self.showHeight);
    [view addSubview:self];
    [self reload];
}

- (void)reload
{

    CGFloat xOffset = 20;
    NSInteger number = 0;
    if (self.dataSource && [self.dataSource respondsToSelector:@selector(numberOfDeviceView)]) {
        number = [self.dataSource numberOfDeviceView];
    }
    for (int i = 0; i < number; i++) {
        //计算Header
        if (self.dataSource && [self.dataSource respondsToSelector:@selector(deviceListView:heightForHeaderViewAtIndex:)]) {
            xOffset += [self.dataSource deviceListView:self heightForHeaderViewAtIndex:i];
        }
        //计算 deviceView本身

        CGFloat height = 0;
        if (self.dataSource && [self.dataSource respondsToSelector:@selector(deviceListView:heightForDeviceViewAtIndex:)]) {
            height = [self.dataSource deviceListView:self heightForDeviceViewAtIndex:i];
        }

        if (self.dataSource && [self.dataSource respondsToSelector:@selector(deviceListView:deviceViewForDeviceListViewIndex:)]) {
            DeviceView* deviceView = [self.dataSource deviceListView:self deviceViewForDeviceListViewIndex:i];
            deviceView.tag = 1000 + i;

            [deviceView addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];

            deviceView.frame = CGRectMake(xOffset, 0, height, 50);
            [self addSubview:deviceView];
            xOffset += height;
        }
        //计算 footer
        if (self.dataSource && [self.dataSource respondsToSelector:@selector(deviceListView:heightForFooterViewAtIndex:)]) {
            xOffset += [self.dataSource deviceListView:self heightForFooterViewAtIndex:i];
        }
    }
}
- (void)click:(UIControl*)control
{

    if (self.delegate && [self.delegate respondsToSelector:@selector(deviceListView:didSelectDeviceAtIndex:)]) {
        [self.delegate deviceListView:self didSelectDeviceAtIndex:control.tag - 1000];
    }
}
@end
